<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Users_rights extends CI_Controller {
	var $perpage = 10;

		public function __construct() {
		   parent::__construct();
		   if (!$this->ion_auth->logged_in() || !$this->ion_auth->is_admin()) redirect('auth/login/'.str_replace("/", ".",$_SERVER['REQUEST_URI']));
		   $this->layout->setlayout('admin/layout');
		   $this->crumps->push('/admin/users_rights/', 'Права доступа');
		   $this->users_rights_model->check_rights(strtolower(get_class()), $this->router->get_method());
	   }

	public function index()	{
		$data['from'] = $from = $this->input->get('from', true);
		if ($from == "") $from = 0;
		$data['pages'] = $pages = $this->db->select()->from('groups')->limit($this->perpage, $from)->get()->result_array();

		/* pagination */
		$count = $this->db->select()->from('users')->count_all_results();
		if ($from != 0 && sizeof($pages) <= 0 && $count > 0) {
			$pgng = $from - $this->perpage;
			redirect('admin/users_rights/index/?from='.$pgng);
		}
		$this->load->library('pagination');
		$config['base_url'] = '/admin/users_rights/';
		$config['total_rows'] = $count;
		$config['per_page'] = $this->perpage;
		$this->pagination->initialize($config);
		$data['paging'] = $this->pagination->create_links();
		/* pagination */

		$this->layout->view('admin/users_rights/index', $data);
	}
	public function edit($id = 0) {
		$this->crumps->push('/admin/users_rights/'.($id == 0?'add':'edit/'.$id).'/', ($id == 0?"Добавление":"Редактирование"));
		$functions = $this->users_rights_model->get_all_list();

		$group = $this->ion_auth->get_group($id);

		$form = new jQuickForm('rights_form');

		$form->addElement('hidden', 'sended');

		$form->setLabel(($id == 0?"Добавление":"Редактирование").' прав группы пользователей '.$group->description);

		$gr = $form->insertGroup()->addClass('col col2');

		foreach ($functions as $key => $class) {
			$page = $this->db->select()->from('rights')->where('right_group', $id)->where('right_block', $key)->get()->row_array();
			$fieldset = $form->insertFieldset()->setLabel($key)->addClass('field_rights')->setAttribute('rel', $key);
			$gr = $fieldset->insertGroup()->addClass('chk')->addClass('col col3');
			$chk = $gr->insertInputCheckbox('rights['.$key.'][all]', 1)->setLabel('Все привелегии')->addClass('all_rights')->setAttribute('rel', $key);
			if ($page['right_all'] == 1) $chk->setAttribute('checked', 'checked');
			$allowed = json_decode($page['right_functions'], true);
			foreach ($class as $method) {
				$chk = $gr->insertInputCheckbox('rights['.$key.']['.$method.']', 1)->setLabel($method)->setAttribute('rel', $key);
				if ($allowed[$method] == 1 || $page['right_all'] == 1) $chk->setAttribute('checked', 'checked');
			}
		}
		if ($_SERVER['REQUEST_METHOD'] == "POST" && $form->validate()) {
			$p_data = $this->input->post();

			$this->db->where('right_group', $id)->delete('rights');
			if (sizeof($p_data['rights']) > 0) {
				foreach ($p_data['rights'] as $key => $group) {
					$up_data = array();
					$up_data['right_id'] = 0;
					$up_data['right_group'] = $id;
					$up_data['right_block'] = $key;
					$up_data['right_all'] = ($group['all'] != ""?$group['all']:0);
					unset($group['all']);
					foreach ($functions[$key] as $need) {
						if (!array_key_exists($need, $group)) {
							$group[$need] = 0;
						} else {
							$group[$need] = 1;
						}
					}
					$up_data['right_functions'] = json_encode($group);
					$this->db->insert('rights', $up_data);
				}
			} else {
				foreach ($functions as $key => $gr) {
					$up_data = array();
					$up_data['right_id'] = 0;
					$up_data['right_group'] = $id;
					$up_data['right_block'] = $key;
					$up_data['right_all'] = 0;
					foreach ($gr as $one) {
						$up_group[$one] = 0;
					}
					$up_data['right_functions'] = json_encode($up_group);
					$this->db->insert('rights', $up_data);
				}
			}

			$this->session->set_flashdata('msg', 'Успешно обновлено');
			redirect('admin/users_rights/edit/'.$id.'/');
		}
		$form->insertInputSubmit(($id == 0?"Добавить":"Сохранить"));

		$form->addDataSource(new HTML_QuickForm2_DataSource_Array($page));
		$data['form'] = $form."";
		$data['js'] = jQuickForm::js()->getJsAll();
		$this->layout->view('admin/users_rights/edit', $data);
	}
}